package controllers;

import java.util.List;

import models.Recipe;
import play.data.Upload;
import play.data.binding.Binder;
import play.data.validation.Validation;
import play.exceptions.TemplateNotFoundException;
import play.i18n.Messages;
import play.modules.siena.SienaModelUtils;
import play.modules.siena.SienaPlugin;
import play.mvc.Controller;
import play.mvc.Http.Request;
import play.mvc.With;
import controllers.CRUD.For;

/**
 * @author oleksandr.bezhan
 * 
 *         Apr 30, 2012
 */
@With(Secure.class)
@For(Recipe.class)
public class Recipes extends CRUD {
    public static void save(String id) throws Exception {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Recipe object = new Recipe();
        object.id = Long.parseLong(id);
        object.get();
        notFoundIfNull(object);
        Binder.bind(object, "object", Controller.params.all());
        List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
        for (Upload upload : uploads) {
            if (upload.getSize() > 0) {
                if (upload.getFieldName().equals("image")) {
                    object.image = new com.google.appengine.api.datastore.Blob(upload.asBytes());
                } else if (upload.getFieldName().equals("thumb")) {
                    object.thumb = new com.google.appengine.api.datastore.Blob(upload.asBytes());
                }
            }
        }
        // if (image != null) {
        // object.image = new com.google.appengine.api.datastore.Blob(FileUtils.readFileToByteArray(image.getFile()));
        // }
        // if (thumb != null) {
        // object.thumb = new com.google.appengine.api.datastore.Blob(FileUtils.readFileToByteArray(thumb.getFile()));
        // }
        Controller.validation.valid(object);
        if (Validation.hasErrors()) {
            Controller.renderArgs.put("error", Messages.get("crud.hasErrors"));
            try {
                render(Controller.request.controller.replace(".", "/") + "/show.html", type, object);
            } catch (TemplateNotFoundException e) {
                render("CRUD/show.html", type, object);
            }
        }
        SienaPlugin.pm().save(object);

        Controller.flash.success(Messages.get("crud.saved", type.modelName));
        if (Controller.params.get("_save") != null) {
            redirect(Controller.request.controller + ".list");
        }
        redirect(Controller.request.controller + ".show", SienaModelUtils.keyValue(object));
    }
}
